package com.bytedance.danmaku.render.engine.demo.danmu.bordertext

import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.PorterDuff
import android.graphics.PorterDuffColorFilter
import android.graphics.RectF
import com.bytedance.danmaku.render.engine.control.DanmakuConfig
import com.bytedance.danmaku.render.engine.data.DanmakuData
import com.bytedance.danmaku.render.engine.demo.utils.DRAW_TYPE_AUTO_SIZE_BITMAP
import com.bytedance.danmaku.render.engine.render.draw.DrawItem
import com.bytedance.danmaku.render.engine.render.draw.IDrawItemFactory

/**
 * @Description:自定义可随config调整大小的bitmap 弹幕
 * @Author yanxin
 * @Date:  2025/8/22
 */

class AutoSizeBitmapDanmaku: DanmakuData() {

    override var drawType: Int = DRAW_TYPE_AUTO_SIZE_BITMAP

    /**
     * The bitmap will not be automatically recycled,
     * and occupy the memory before you recycle it manually.
     * Please check the memory problems carefully.
     */
    var bitmap: Bitmap? = null
    /**
     * TintColor will be used with the mode of [android.graphics.PorterDuff.Mode.SRC_IN]
     */
    var tintColor: Int? = null
    /**
     * Zero means using the origin width of the bitmap
     */
    var width: Float = 0F
    /**
     * Zero means using the origin height of the bitmap
     */
    var height: Float = 0F
}
class AutoSizeBitmapDrawItem: DrawItem<AutoSizeBitmapDanmaku>() {

    private val mBitmapPaint = Paint(Paint.ANTI_ALIAS_FLAG or Paint.DITHER_FLAG)
    private val mRectF = RectF()

    override fun getDrawType(): Int {
        return DRAW_TYPE_AUTO_SIZE_BITMAP
    }

    override fun onBindData(data: AutoSizeBitmapDanmaku) {
        mBitmapPaint.flags = Paint.ANTI_ALIAS_FLAG or Paint.DITHER_FLAG
    }

    override fun onMeasure(config: DanmakuConfig) {
        val width = data?.width ?: config.text.size
        val height = data?.height ?: config.text.size
        if (width > 0 && height > 0) {
            this.width = width
            this.height = height
        } else {
            this.width = data?.bitmap?.width?.toFloat() ?: 0F
            this.height = data?.bitmap?.height?.toFloat() ?: 0F
        }
    }

    override fun onDraw(canvas: Canvas, config: DanmakuConfig) {
        data?.bitmap?.let { bitmap ->
            mRectF.set(x, y, x + width, y + height)
            val tint = data?.tintColor
            mBitmapPaint.colorFilter = if (tint == null) null else PorterDuffColorFilter(tint, PorterDuff.Mode.SRC_IN)
            canvas.drawBitmap(bitmap, null, mRectF, mBitmapPaint)
        }
    }

    override fun recycle() {
        super.recycle()
        mBitmapPaint.reset()
        mRectF.set(0F, 0F, 0F, 0F)
    }
}
class AutoSizeBitmapDrawItemFactory: IDrawItemFactory {

    override fun getDrawType(): Int {
        return DRAW_TYPE_AUTO_SIZE_BITMAP
    }

    override fun generateDrawItem(): DrawItem<out DanmakuData> {
        return AutoSizeBitmapDrawItem()
    }

}